<template>
  <div class="label-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="780px"
      align-center
    >
      <div>
        <el-divider class="dialog-divider" />
        <div class="mt-[10px] p-[5px]">
          <div class="title-box flex mb-[10px]">
            <div><span class="font-bold">标签类型</span></div>
          </div>
          <el-tabs
            v-model="activeTab"
            tab-position="left"
            class="demo-tabs"
            @tab-click="handleTabChange"
          >
            <el-tab-pane
              v-for="(tab, index) in tabs"
              :key="`${tab}-${index}`"
              :name="String(index)"
              :lazy="true"
            >
              <template #label>
                <div class="custom-tabs-label w-[168px]">
                  <el-icon><calendar /></el-icon>
                  <span class="ml-[5px]">{{ tab }}</span>
                </div>
              </template>
              <el-scrollbar class="p-[10px] h-[580px]" height="580px">
                <!-- el-tabs 嵌套多个 el-form 导致ref引用数组化 -->
                <el-form
                  :ref="(el: any) => setFormRef(el, index)"
                  :model="ruleForm"
                  :rules="formFule"
                  label-width="80"
                  class="demo-ruleForm"
                  status-icon
                >
                  <FormField label="类型名称" prop="name">
                    <el-input
                      v-model="ruleForm.name"
                      maxlength="15"
                      placeholder="请输入类型名称"
                      show-word-limit
                    />
                  </FormField>

                  <FormField label="输入类型" prop="type">
                    <el-radio-group v-model="ruleForm.type">
                      <el-radio :value="'1'">单选</el-radio>
                      <el-radio :value="'2'">多选</el-radio>
                      <el-radio :value="'3'">文本</el-radio>
                    </el-radio-group>
                  </FormField>

                  <FormField label="排序" prop="typeSort">
                    <el-input-number
                      style="width: 100%"
                      v-model="ruleForm.typeSort"
                      controls-position="right"
                    />
                  </FormField>

                  <FormField label="必填" prop="required">
                    <el-switch v-model="ruleForm.required" />
                  </FormField>

                  <!-- 标签选项 -->
                  <template
                    v-if="ruleForm.type === '1' || ruleForm.type === '2'"
                  >
                    <el-form-item label="标签选项" prop="optionsList">
                      <VueDraggable
                        v-model="ruleForm.optionsList"
                        :animation="150"
                        handle=".handle"
                        class="flex flex-col gap-4 w-full"
                      >
                        <div
                          v-for="(item, index) in ruleForm.optionsList"
                          :key="item.id"
                        >
                          <el-row :gutter="20" class="w-full">
                            <el-col :span="20">
                              <div>
                                <el-input
                                  v-model="item.options"
                                  placeholder="请输入选项名称"
                                >
                                  <template #prepend>
                                    <el-button
                                      class="handle"
                                      :icon="Rank"
                                      style="color: #000"
                                    />
                                  </template>
                                </el-input>
                              </div>
                              <div class="mt-[12px]">
                                <el-input
                                  v-model="item.comment"
                                  placeholder="请输入选项描述"
                                />
                              </div>
                            </el-col>
                            <el-col v-show="index !== 0" :span="4">
                              <el-popconfirm
                                confirm-button-text="确定"
                                cancel-button-text="取消"
                                :title="`确认要删除${item.options ? ` [${item.options}] ` : ''}标签吗？`"
                                @confirm="deleteLabelSelect(index)"
                              >
                                <template #reference>
                                  <Delete
                                    class="text-[red] cursor-pointer"
                                    style="width: 1em; height: 1em"
                                  />
                                </template>
                              </el-popconfirm>
                            </el-col>
                          </el-row>
                        </div>
                      </VueDraggable>
                      <p
                        class="text-[#8c96ff] text-[12px] cursor-pointer"
                        @click="insertLabelSelect"
                      >
                        添加选项标签
                      </p>
                    </el-form-item>
                  </template>

                  <!-- 互斥规则 -->
                  <template v-if="ruleForm.type === '2'">
                    <el-form-item label="互斥规则" prop="rules">
                      <div class="w-full">
                        <div
                          v-for="(rule, index) in ruleForm.rules"
                          :key="`${rule}-${index}`"
                          class="rule-item"
                        >
                          <el-row :gutter="20" class="w-full items-center">
                            <el-col :span="20">
                              <DualSelect
                                :modelValue="rule"
                                @update:modelValue="
                                  (value) => updateRule(index, value)
                                "
                                :options="sharedOptions"
                              />
                            </el-col>

                            <!-- 删除按钮 -->
                            <el-col :span="4" class="flex justify-end">
                              <el-popconfirm
                                confirm-button-text="确定"
                                cancel-button-text="取消"
                                :title="`确认要删除该互斥规则吗？`"
                                @confirm="deleteRule(index)"
                              >
                                <template #reference>
                                  <Delete
                                    class="text-[red] cursor-pointer"
                                    style="width: 1em; height: 1em"
                                  />
                                </template>
                              </el-popconfirm>
                            </el-col>
                          </el-row>
                        </div>

                        <!-- 添加按钮 -->
                        <p
                          class="text-[#8c96ff] text-[12px] cursor-pointer"
                          @click="() => ruleForm.rules.push('')"
                        >
                          添加互斥规则
                        </p>
                      </div>
                    </el-form-item>
                  </template>

                  <template v-if="ruleForm.type === '3'">
                    <FormField label="字数限制" prop="limit">
                      <el-input-number
                        style="width: 100%"
                        v-model="ruleForm.limit"
                        controls-position="right"
                      />
                    </FormField>
                    <FormField label="标签说明" prop="commit">
                      <el-input
                        v-model="ruleForm.commit"
                        placeholder="请输入标签说明"
                        clearable
                      />
                    </FormField>
                  </template>
                </el-form>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" size="default">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, defineAsyncComponent } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { VueDraggable } from 'vue-draggable-plus';
  import { RuleForm } from '@/types/mark';
  import { Rank } from '@element-plus/icons-vue';

  const FormField = defineAsyncComponent(
    () => import('./components/FormField.vue'),
  );

  const DualSelect = defineAsyncComponent(
    () => import('@/components/DualSelect.vue'),
  );

  const sharedOptions = ref([
    { value: '选项1', label: '选项1' },
    { value: '选项2', label: '选项2' },
    { value: '选项3', label: '选项3' },
  ]);

  // 定义子组件向父组件传值/事件
  const emit = defineEmits(['refresh']);

  const tabs = ref(['User', 'Route', 'Config', 'Role']);

  // 当前激活的 Tab 索引
  const activeTab = ref<string>('0');
  const formRefs = ref<FormInstance[]>([]);

  const state = reactive({
    dialog: {
      type: '',
      title: '',
      isShowDialog: false,
    },
  });
  const ruleForm = reactive<RuleForm>({
    name: '',
    typeSort: undefined,
    required: false,
    type: '3',
    limit: 500,
    commit: '',
    optionsList: [
      {
        options: '',
        comment: '',
        id: '1',
      },
    ],
    rules: [],
  });

  const formFule = reactive<FormRules<RuleForm>>({
    name: [
      {
        required: true,
        message: '请输入类型名称',
        trigger: 'blur',
      },
    ],
    limit: [
      {
        required: true,
        message: '请输入字数限制',
      },
      { type: 'number', message: '请输入数字' },
    ],
    commit: [
      {
        required: true,
        message: '请输入标签说明',
        trigger: 'blur',
      },
    ],
  });

  // 切换table
  const handleTabChange = (tab: any) => {
    activeTab.value = tab.index;
    formRefs.value[tab.index]?.resetFields(); //有后端切换成后端数据
  };

  // 添加选项标签
  const insertLabelSelect = () => {
    ruleForm.optionsList.push({
      options: '',
      comment: '',
      id: `${ruleForm.optionsList.length + 1}`,
    });
  };

  // 删除选项标签
  const deleteLabelSelect = (index: number) => {
    if (ruleForm.optionsList.length <= 1) {
      return;
    }

    ruleForm.optionsList.splice(index, 1);
  };

  // 更新互斥规则
  const updateRule = (index: number, value: string) => {
    ruleForm.rules[index] = value;
  };

  // 删除互斥规则
  const deleteRule = (index: number) => {
    ruleForm.rules.splice(index, 1);
  };

  // 动态设置表单引用
  const setFormRef = (el: any, index: number) => {
    if (el) formRefs.value[index] = el;
  };

  // 打开弹窗
  const openDialog = (type: string = 'create') => {
    state.dialog.type = type;
    state.dialog.title = type === 'create' ? '新建标签' : '编辑标签';
    state.dialog.isShowDialog = true;
  };

  // 关闭弹窗
  const closeDialog = () => {
    state.dialog.isShowDialog = false;
    formRefs.value.forEach((formEl) => {
      if (formEl) formEl.resetFields(); // 重置所有表单
    });
  };

  // 取消
  const onCancel = () => {
    closeDialog();
  };

  // 提交
  const handleSubmit = async () => {
    const currentForm = formRefs.value[Number(activeTab.value)];
    if (!currentForm) {
      console.error('当前表单实例未找到');
      return;
    }

    try {
      await currentForm.validate(); // ✅ 针对当前激活的表单实例校验
      closeDialog();
      emit('refresh'); //刷新标签表格
      currentForm.resetFields();
    } catch (error) {
      console.error('验证失败:', error);
    }
  };

  // 暴露变量
  defineExpose({
    openDialog,
  });
</script>

<style lang="scss" scoped>
  .dialog-divider {
    margin: 0 !important;
  }
  .demo-tabs {
    height: 580px;

    .custom-tabs-label {
      display: flex;
      align-items: center;
      padding: 0 !important;
      font-size: 14px;
      color: #333;
      /* 可选：处理长标签换行 */
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  :deep(.is-left) {
    padding: 0 !important;
  }
  .handle {
    cursor: move;
    color: #000;
  }
</style>
